package com.bugreport.trackers.mantis128;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.math.BigInteger;

import org.junit.Test;
import org.unitils.UnitilsJUnit4;
import org.unitils.dbunit.annotation.DataSet;
import org.unitils.dbunit.annotation.ExpectedDataSet;
import org.unitils.spring.annotation.SpringApplicationContext;
import org.unitils.spring.annotation.SpringBeanByType;

import com.bugreport.trackers.clients.mantis128.IssueData;
import com.bugreport.trackers.clients.mantis128.MantisConnectPortType;

@DataSet
@SpringApplicationContext("com/bugreport/trackers/mantis128/spring-client.xml")
public class Mantis128ClientTestCase extends UnitilsJUnit4 {

	@SpringBeanByType
	private MantisConnectPortType client;

	@SpringBeanByType
	private Mantis128TestConfiguration config;

	private IssueData newIssueWithSummaryAndDescription() {
		return IssueDataProxy.newIssue(config.getSummary(), config.getDescription(), config.getProjectId(),
				config.getCategoryName());
	}

	private BigInteger createIssueWithSummaryAndDescriptionAndTest() throws Exception {

		IssueData issue = newIssueWithSummaryAndDescription();
		BigInteger issueId = client.mc_issue_add(config.getUserLogin(), config.getUserPassword(), issue);

		assertNotNull(issueId);
		assertTrue(issueId.doubleValue() > 0);

		return issueId;
	}

	@Test
	@ExpectedDataSet
	public void createIssueWithSummaryAndDescription() throws Exception {
		createIssueWithSummaryAndDescriptionAndTest();
	}

	@Test
	@ExpectedDataSet
	public void createIssueAndAddAttachment() throws Exception {

		BigInteger issueId = createIssueWithSummaryAndDescriptionAndTest();
		BigInteger attachmentId = client.mc_issue_attachment_add(config.getUserLogin(), config.getUserPassword(),
				issueId, config.getAttachmentFileName(), config.getAttachmentFileType(), config
						.getAttachmentFileContent().getBytes());

		assertNotNull(attachmentId);
		assertTrue(attachmentId.doubleValue() > 0);

		byte[] attachment = client.mc_issue_attachment_get(config.getUserLogin(), config.getUserPassword(),
				attachmentId);

		assertArrayEquals(config.getAttachmentFileContent().getBytes(), attachment);
	}
}
